<template>
    <div class="main-map-bg">
        <div id="safety-warining-map" style="height:100%"></div>
        <!-- 创建方案弹出窗口 -->
        <div class="fixed-wrap" v-if="isShowCreatedPlan">
            <div class="created-plan">
                <div class="c-tip">
                    保存方案
                    <a class="icon-times" @click="closeCreatedPlan"></a>
                </div>
                <div class="input-p-name d-flex">
                    <label>方案名称：</label>
                    <input
                        type="text"
                        maxlength="12"
                        class="form-control"
                        placeholder
                        v-model="planName"
                    >
                </div>
                <div>
                    <button class="save-btn" @click="saveSecurityFence">保存</button>
                </div>
            </div>
        </div>
    </div>
</template>


 <script type="text/javascript">
import BMap from "BMap";
export default {
    name: "baiduMapSafetyWarning",
    data() {
        return {
            districtLoading: 0, //百度地图区域化个数
            blist: [], //百度地图遮罩集合
            deviceMarker: [], //用于存放旧的设备点的坐标，在请求之后，清除原来的点
            drivceLists: [],
            drivceList: [],
            isShowCreatedPlan: false,
            securityFence: [], //安全围栏保存的数组
            palnList: [], //所以安全围栏的数组
            planName: "", //安全围栏的名字
            isOpenDrawManager: true, //是否展示工具栏
            drawingManager: "", //围栏绘图工具
            styleOptions: {
                //绘图工具选项
                strokeColor: "#e60012", //边线颜色。
                fillColor: "#e60012", //填充颜色。当参数为空时，圆形将没有填充效果。
                strokeWeight: 3, //边线的宽度，以像素为单位。
                strokeOpacity: 0.8, //边线透明度，取值范围0 - 1。
                fillOpacity: 0.2, //填充的透明度，取值范围0 - 1。
                strokeStyle: "dashed" //边线的样式，solid或dashed。
            },
            overlays: [], //已经画好的安全围栏
            taskOfAddMarket: "" //任务
        };
    },
    methods: {
        /* ***************初始化百度地圖begin**************   */
        initSafetyWariningBaiduMap: function() {
            var map = new BMap.Map("safety-warining-map", {
                enableMapClick: false
            });
            map.centerAndZoom(new BMap.Point(114.77778, 32.089846), 10);
            // map.centerAndZoom("信阳市",10);
            map.enableScrollWheelZoom();
            map.disableDoubleClickZoom(); //禁止双击缩放
            map.enableScrollWheelZoom(true);
            this.addDistrict("信阳");
            //渲染个性化百度地图
            addindividuation(map);
            map.addEventListener("click", function(e) {
                console.log(e.point);
            });
            window.SafetyWariningMap = map; //将map变量储存在全局
        },
        /* ***************初始化百度地圖end**************   */
        /* ***************区域化百度地圖begin**************   */
        addDistrict: function(districtName) {
            var _this = this;
            //使用计数器来控制加载过程
            _this.districtLoading++;
            var bdary = new BMap.Boundary();

            bdary.get(districtName, function(rs) {
                //获取行政区域
                var count = rs.boundaries.length; //行政区域的点有多少个
                if (count === 0) {
                    alert("未能获取当前输入行政区域");
                    return;
                }
                for (var i = 0; i < count; i++) {
                    _this.blist.push({
                        points: rs.boundaries[i],
                        name: districtName
                    });
                }
                //加载完成区域点后计数器-1
                _this.districtLoading--;
                if (_this.districtLoading == 0) {
                    //全加载完成后画端点
                    _this.drawBoundary();
                }
            });
        },
        drawBoundary: function() {
            var _this = this;
            //包含所有区域的点数组
            var pointArray = [];

            /*画遮蔽层的相关方法
             *思路: 首先在中国地图最外画一圈，圈住理论上所有的中国领土，然后再将每个闭合区域合并进来，并全部连到西北角。
             *      这样就做出了一个经过多次西北角的闭合多边形*/

            //定义中国东南西北端点，作为第一层
            var pNW = { lat: 59.0, lng: 73.0 };
            var pNE = { lat: 59.0, lng: 136.0 };
            var pSE = { lat: 3.0, lng: 136.0 };
            var pSW = { lat: 3.0, lng: 73.0 };
            //向数组中添加一次闭合多边形，并将西北角再加一次作为之后画闭合区域的起点
            var pArray = [];
            pArray.push(pNW);
            pArray.push(pSW);
            pArray.push(pSE);
            pArray.push(pNE);
            pArray.push(pNW);
            //循环添加各闭合区域
            for (var i = 0; i < this.blist.length; i++) {
                //添加显示用标签层
                var label = new BMap.Label(this.blist[i].name, {
                    offset: new BMap.Size(20, -10)
                });
                label.hide();
                window.SafetyWariningMap.addOverlay(label);

                //添加多边形层并显示
                var ply = new BMap.Polygon(this.blist[i].points, {
                    strokeWeight: 3,
                    strokeColor: "#1157a4",
                    fillOpacity: 0.01,
                    fillColor: " #FFFFFF"
                }); //建立多边形覆盖物
                /**
                 * 各种鼠标事件绑定
                 */
                function click(evt) {
                    for (var i = 0; i < _this.deviceMarker.length; i++) {
                        _this.deviceMarker[i].closeInfoWindow();
                    }
                }
                function mouseover(evt) {}
                function mousemove(evt) {}
                function mouseout(evt) {}

                ply.name = this.blist[i].name;
                ply.label = label;
                ply.addEventListener("click", click);
                ply.addEventListener("mouseover", mouseover);
                ply.addEventListener("mouseout", mouseout);
                ply.addEventListener("mousemove", mousemove);
                window.SafetyWariningMap.addOverlay(ply);

                //添加名称标签层
                //  var centerlabel = new BMap.Label(blist[i].name, { offset: new BMap.Size(0, 0) });
                // centerlabel.setPosition(ply.getBounds().getCenter());
                //  map.addOverlay(centerlabel);

                //将点增加到视野范围内
                var path = ply.getPath();
                pointArray = pointArray.concat(path);
                //将闭合区域加到遮蔽层上，每次添加完后要再加一次西北角作为下次添加的起点和最后一次的终点
                pArray = pArray.concat(path);
                pArray.push(pArray[0]);
            }

            //限定显示区域，需要引用api库
            var boundply = new BMap.Polygon(pointArray);
            // BMapLib.AreaRestriction.setBounds(map, boundply.getBounds());
            // window.SafetyWariningMap.setViewport(pointArray); //调整视野

            //添加遮蔽层
            var plyall = new BMap.Polygon(pArray, {
                strokeOpacity: 0.0000001,
                strokeColor: "#000000",
                strokeWeight: 0.00001,
                fillColor: "#ffffff",
                fillOpacity: 1
            }); //建立多边形覆盖物
            //  map.addOverlay(plyall);
        },

        /* ***************区域化百度地圖end**************   */

        /* ***************创建百度地图点的坐标加信息框begin**************   */
        createMarket: function(node, info_html) {
            var myIcon = new BMap.Icon(
                "static/img/icon_drivce_small.png",
                new BMap.Size(37, 45)
            );
            var marker = new BMap.Marker(new BMap.Point(node.lng, node.lat), {
                icon: myIcon
            });
            var opts = {
                width: 200, // 信息窗口宽度
                height: 100, // 信息窗口高度
                title: "<div>设备信息</div>", // 信息窗口标题
                enableMessage: true, //设置允许信息窗发送短息
                message: "设备信息message"
            };

            marker.addEventListener("mouseover", function(e) {
                var myIcon = new BMap.Icon(
                    "static/img/icon_drivce_big.png",
                    new BMap.Size(54, 67)
                );
                marker.setIcon(myIcon);
                //  this.openInfoWindow(new BMap.InfoWindow(info_html, opts));
            });
            marker.addEventListener("mouseout", function(e) {
                var myIcon = new BMap.Icon(
                    "static/img/icon_drivce_small.png",
                    new BMap.Size(37, 45)
                );
                marker.setIcon(myIcon);
                // this.closeInfoWindow();
            });

            marker.addEventListener("click", function(e) {
                this.openInfoWindow(new BMap.InfoWindow(info_html, opts));
            });
            return marker;
        },
        /* ***************创建百度地图点的坐标加信息框end**************   */

        //关闭closeCreatedPlan窗口
        closeCreatedPlan() {
            this.isShowCreatedPlan = false;
        },
        isWithinLimits: function() {
            var notify = "";
            //判断所有点是否有进入圈的
            for (var i = 0; i < this.deviceMarker.length; i++) {
                for (var j = 0; j < overlays.length; j++) {
                    if (
                        BMapLib.GeoUtils.isPointInPolygon(
                            this.deviceMarker[i].getPosition(),
                            overlays[j]
                        )
                    ) {
                        var label = this.deviceMarker[i].getLabel();
                        deviceIntoSaftRange.push(
                            this.deviceMarker[i].getTitle()
                        );
                        window.SafetyWariningMap.addOverlay(
                            this.deviceMarker[i]
                        );
                        if (label != null) {
                            notify =
                                notify +
                                label.getContent() +
                                "进入安全范围" +
                                "<br/>";
                        }
                    }
                }
            }
            //判断原来进入圈的是否出了圈
            for (var m = 0; m < this.deviceMarker.length; m++) {
                for (var x = 0; x < deviceIntoSaftRange.length; x++) {
                    if (
                        this.deviceMarker[m].getTitle() ==
                        deviceIntoSaftRange[x]
                    ) {
                        for (var n = 0; n < overlays.length; n++) {
                            if (
                                !BMapLib.GeoUtils.isPointInPolygon(
                                    this.deviceMarker[m].getPosition(),
                                    overlays[n]
                                )
                            ) {
                                var label = this.deviceMarker[m].getLabel();
                                if (label != null) {
                                    notify =
                                        notify +
                                        label.getContent() +
                                        "出了安全范围" +
                                        "<br/>";
                                }
                                deviceIntoSaftRange.splice(x, 1); // 将使后面的元素依次前移，数组长度减1
                                x--; // 如果不减，将漏掉一个元素
                            }
                        }
                    }
                }
            }

            $("#deviceNotify").html(notify);
        },

        setPalnList: function() {
            this.$emit("getPalnList", this.palnList); //主要是通过$emit方法来实现传参的方式，第一个参数是自定义事件名称，第二个则是要传的数据
        },

        isCreatedPlan: function() {
            if (this.isOpenDrawManager == true) {
                this.isOpenDrawManager = false;
                //   $('.BMapLib_Drawing_panel').hide()
            } else {
                this.isOpenDrawManager = true;
                //   $('.BMapLib_Drawing_panel').show()
                for (var i = 0; i < this.overlays.length; i++) {
                    //清除已经画好的安全围栏
                    window.SafetyWariningMap.removeOverlay(this.overlays[i]);
                }
                this.overlays = []; //初始化
            }
        }
    },

    watch: {},
    mounted: function() {
        //挂载页面
        //this.getPlants();
        this.initSafetyWariningBaiduMap();
        //    this.taskOfAddMarket= window.setInterval(() => {
        //    window.setTimeout( this.addMarketToMap(), 0)
        // }, 7000);

        // ************************判断绘制多边形安全栏beign********************************//

        var _this = this;
    },
    destroyed: function() {
        //页面销毁
        window.clearInterval(this.taskOfAddMarket);
    }
};
</script>


